package com.hk.servlet;

import com.alibaba.fastjson.JSONObject;
import com.hk.model.vo.UploadImage;
import com.hk.model.vo.UploadImageVO;
import com.hk.service.IUploadImageService;
import com.hk.service.impl.UploadImageServiceImpl;
import com.hk.utils.CharacterEncoding;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;


/**
 * @Author: zhe
 * @Date: 2021/6/17 15:08
 * @Statement:  上传图片
 */
@WebServlet("/upload/UploadImage")
public class UploadImageServlet extends HttpServlet {

    /**
     * 1、需要上传路径
     * 2、需要request
     * 3、临时文件存储路径
     *
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        CharacterEncoding.setCharacterEncodingResp(req,resp,"UTF-8");
        //        获取当前请求的协议、IP、端口
        String url = req.getScheme()+"://"+req.getServerName()+":"+req.getServerPort();
//        当前时间设置模板
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
        String date = format.format(new Date());
//        图片存放路径
        String imageFileUrl = "/img"+"/"+date+"/";
        String uploadPath = req.getSession().getServletContext().getRealPath(imageFileUrl);
        File file = new File(uploadPath);
//        判断该路径是否存在或创建
        if (!file.exists()) {
            file.mkdirs();
        }
        System.out.println("上传文件到："+uploadPath);
//        System.out.println("当前网址:"+imagePath);
        //设置工厂的临时文件目录：当上传文件的大小大于缓冲区大小时，将使用临时文件目录缓存上传的文件
        String temporary = "D:/temporary";
        IUploadImageService iUploadImageService = new UploadImageServiceImpl();
        String fileName = iUploadImageService.uploadImage(uploadPath, req, temporary);
        PrintWriter out = resp.getWriter();
        String img = url+imageFileUrl+fileName;
        if (!fileName.equals(null)) {
            UploadImage uploadImage = new UploadImage(img, fileName);
            UploadImageVO uploadImageVO = new UploadImageVO(0, "success", uploadImage);
            String uploadImageVOJSON = JSONObject.toJSONString(uploadImageVO);
            out.println(uploadImageVOJSON);
        } else {
            UploadImage uploadImage = new UploadImage(img, fileName);
            UploadImageVO uploadImageVO = new UploadImageVO(1, "error", uploadImage);
            String uploadImageVOJSON = JSONObject.toJSONString(uploadImageVO);
            out.println(uploadImageVOJSON);
        }
        out.flush();
        out.close();

    }
}
